/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */

Ext.namespace("Org");


/**
 * Area edit dialog.
 *
 * @param config the configuration.
 */
Org.UnitDialog = function(config) {
	Org.UnitDialog.superclass.constructor.call(this, config);
};

Ext.extend(Org.UnitDialog, Ext.Window, {

	initComponent: function() {

		Ext.apply(this, {
			renderTo: Ext.getBody(),
			modal: true,
			iconCls: 'icon-unit-add',
			title: MSG['unit.new'],
			bodyStyle:'padding:5px'
		});

		this.items = new Ext.FormPanel({
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'hidden',
				name: 'unit'
			}, {
				xtype: 'textfield',
				name: 'code',
				fieldLabel: MSG['unit.code'],
				maxLength: 20,
				allowBlank: false
			},{
				xtype: 'textfield',
				name: 'name',
				fieldLabel: MSG['unit.name'],
				maxLength: 50,
				allowBlank: false
			},{
				xtype: 'textarea',
				name: 'description',
				width: 165,
				fieldLabel: MSG['unit.description'],
				maxLength: 1000,
				allowBlank: false
			}],
			buttons: [{
				text: MSG['button.save'],
				iconCls: 'icon-disk',
				handler: this.onSave,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onCancel,
				scope: this
			}]
		});
		Org.UnitDialog.superclass.initComponent.call(this);
	},

	onSave: function() {
		var theForm = this.items.items[0].getForm();

		theForm.submit({
			url: CONTEXT_PATH + '/secure/orgadmin/unit/update.json',
			method: 'POST',
			clientValidation: true,
			waitTitle: MSG['wait.title'],
			waitMsg: MSG['wait.message'],
			success: this.onSaveSuccess,
			failure: this.onSaveError,
			scope: this
		});
	},

	onCancel: function() {
		this.close();
	},

	onSaveSuccess: function(/*form, action*/) {
		this.close();
		notifySuccess(MSG['unit.new'], MSG['update.success']);
	},

	onSaveError: function(/*form, action*/) {
		notifyError(MSG['unit.new'], MSG['update.error']);
	}

});




/**
 * Qualification Checks Paths associated.
 *
 * @param config the configuration.
 */
Org.UnitCheckDelete = function(config) {
	Org.UnitCheckDelete.superclass.constructor.call(this, config);
};

Ext.extend(Org.UnitCheckDelete, Ext.Window, {

	gridCheck: null,

	checkStore: null,

	waitDlg: null,

	data: null,

	searchPanel: null,

	initComponent: function() {
		Ext.apply(this, {
			layout: 'border',
			width: '70%',
			height: 400,
			renderTo: Ext.getBody(),
			modal: true,
			iconCls: 'icon-unit-find',
			title: MSG['unit.checks'],
			bodyStyle:'padding:5px'
		});

		// Store
		this.checkStore = new Ext.data.JsonStore({
			root: 'results',
			fields:[
				{name: 'id', type: 'int'},
				{name: 'code', type: 'string'},
				{name: 'name', type: 'string'},
				{name: 'surveys', type: 'int'}
			],
			data: Ext.util.JSON.decode(this.data)
		});

		//Custom column plugin for checkcolumn
		var elementsCheckBox = new Ext.grid.CheckboxSelectionModel(),
				columnModel = new Ext.grid.ColumnModel([
					elementsCheckBox,
					{header: MSG['unit.id'], dataIndex: 'id', width: 20, sortable: true},
					{header: MSG['unit.code'], dataIndex: 'code', width: 20, sortable: true},
					{header: MSG['unit.name'], dataIndex: 'name', width: 55, sortable: true},
					{header: MSG['surveys.production'], dataIndex: 'surveys', width: 30, sortable: true}
				]);

		// Grid
		this.gridCheck = new Ext.grid.GridPanel({
			region: 'center',
			viewConfig: {
				emptyText: MSG['pagination.empty'],
				forceFit: true
			},
			cm: columnModel,
			sm: elementsCheckBox,
			store: this.checkStore,
			buttons: [{
				text: MSG['button.validate'],
				iconCls: 'icon-ok',
				handler: this.onRemoveSelected,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onClose,
				scope: this
			}]
		});

		this.gridCheck.getView().getRowClass = function(record/*, index*/){
			return (record.data.surveys > 0 ? 'red-row' : '');
		};

		this.gridCheck.selModel.on('beforerowselect', function(sm, rowIndex, keepExisting, record){
			if (record.get('surveys') > 0){
				notifyError(MSG['error'], MSG['unit.delete.error']);
				return false;
			}
		});

		this.items = [this.gridCheck];
		
		Org.UnitCheckDelete.superclass.initComponent.call(this);
	},

	onRemoveSelected: function(){
		var selections = this.gridCheck.getSelectionModel().getSelections();
		if (selections.length > 0){
			var elements = [];
			for (var i=0; i<selections.length; i++){
				elements.push(selections[i].get('id'));
			}

			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/unit/delete.json',
				success: function(){
						notifySuccess(MSG['delete'], MSG['delete.success']);
				},
				failure: function(){
					notifyError(MSG['delete'], MSG['delete.error']);
				},
				params: { elements: elements }
			});
		};

		this.searchPanel.onReset();

		this.onClose();
	},

	onClose: function(){
		this.close();
	}
});



/**
 * Unit search panel.
 *
 * @param config the configuration.
 */
Org.UnitPanel = function(config) {
	Org.UnitPanel.superclass.constructor.call(this, config);
};

Ext.extend(Org.UnitPanel, Ext.Panel, {

	searchForm: null,

	waitDlg: null,

	resultsStore: null,

	pageToolbar: null,

	resultsGrid: null,

	editForm: null,

	initComponent: function() {
		this.layout = 'border';
		this.title = MSG['units.title'];
		this.closable = true;
		this.autoShow = true;
		this.iconCls = 'icon-unit';

		// Tools
		this.tools = [{
			id: 'close',
			handler: this.onClose,
			scope: this
		}];

		// Search form
		this.searchForm = new Ext.FormPanel({
			region: 'west',
			split: true,
			collapsible: true,
			title: MSG['search.title'],
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'textfield',
				name: 'code',
				fieldLabel: MSG['unit.code'],
				maxLength: 20
			},{
				xtype: 'textfield',
				name: 'name',
				fieldLabel: MSG['unit.name'],
				maxLength: 50
			},{
				xtype: 'textarea',
				name: 'description',
				width: 165,
				fieldLabel: MSG['unit.description'],
				maxLength: 1000
			}, {
				xtype: 'hidden',
				name: 'organization',
				value: Main.app.getUser().organization.id
			}],
			buttons: [{
				text: MSG['button.search'],
				iconCls: 'icon-search',
				handler: this.onSearch,
				scope: this
			}, {
				text: MSG['button.reset'],
				iconCls: 'icon-cancel',
				handler: this.onReset,
				scope: this
			}]
		});

		// Store
		this.resultsStore = new Ext.data.JsonStore({
			url: CONTEXT_PATH + '/secure/orgadmin/unit/find.json',
			root: 'results',
			totalProperty: 'total',
			remoteSort: true,
			fields: ['id', 'code', 'name', 'description']
		});
		
		this.resultsStore.on("beforeload", function() {
					this.waitDlg = Ext.Msg.wait(MSG['wait.title'], MSG['wait.text']);
					this.resultsStore.baseParams = this.searchForm.getForm().getRawValues();
		}, this);

		this.resultsStore.on("load", function() {
					this.waitDlg.hide();
		}, this);

		// Pagination toolbar
		this.pageToolbar = new Ext.PagingToolbar({
			store: this.resultsStore,
			displayInfo: true,
			pageSize: 100,
			plugins: [new Common.PageSizePlugin(MSG['page.size'])],
			items:[
				'-', {
					text: MSG['button.remove'],
					iconCls: 'icon-remove',
					handler: this.onCheckRemoveSelected,
					scope: this
				}
			]
		});

		// Grid
		this.resultsGrid = new Ext.grid.GridPanel({
			title: MSG['result.title'],
			region: 'center',
			viewConfig: {
				emptyText: MSG['pagination.empty'],
				forceFit: true
			},
			cm: new Ext.grid.ColumnModel([
				{header: MSG['unit.id'], dataIndex: 'id', width: 20, sortable: true},
				{header: MSG['unit.code'], dataIndex: 'code', width: 50, sortable: true},
				{header: MSG['unit.name'], dataIndex: 'name', width: 140, sortable: true},
				{header: MSG['unit.description'], dataIndex: 'description', width: 200, sortable: true}
			]),
			store: this.resultsStore,
			bbar: this.pageToolbar
		});

		// Editor
		this.editForm = new Ext.FormPanel({
			region: 'east',
			split: true,
			collapsible: true,
			collapsed: true,
			title: MSG['button.newfem'],
			width: 340,
			labelWidth: 120,
			bodyStyle:'padding: 5px',
			items: [{
				xtype: 'hidden',
				name: 'id',
				value: 0
			}, {
				xtype: 'hidden',
				name: 'organization',
				value: Main.app.getUser().organization.id
			}, {
				xtype: 'textfield',
				name: 'code',
				fieldLabel: MSG['unit.code'],
				maxLength: 20,
				allowBlank: false
			}, {
				xtype: 'textfield',
				name: 'name',
				fieldLabel: MSG['unit.name'],
				maxLength: 50,
				allowBlank: false
			}, {
				xtype: 'textarea',
				name: 'description',
				width: 165,
				fieldLabel: MSG['unit.description'],
				maxLength: 1000,
				allowBlank: false
			}],
			buttons: [{
				text: MSG['button.save'],
				iconCls: 'icon-disk',
				handler: this.onSave,
				scope: this
			}, {
				text: MSG['button.cancel'],
				iconCls: 'icon-cancel',
				handler: this.onCancel,
				scope: this
			}]
		});

		this.items = [this.searchForm, this.resultsGrid, this.editForm];

		this.pageToolbar.doLoad(0);

		this.resultsGrid.on("rowclick", this.onSelected, this);
		// this.resultsGrid.on("rowcontextmenu", this.onContextMenu, this);

		Org.UnitPanel.superclass.initComponent.call(this);
	},

	onClose: function() {
		Main.app.addPanel(null);
	},

	onSearch: function() {
		this.editForm.collapse();
		this.pageToolbar.doLoad(0);
	},

	onReset: function() {
		this.searchForm.getForm().reset();
		this.pageToolbar.doLoad(0);
	},

	onSelected: function(grid, rowIndex/*, evt*/) {
		this.searchForm.collapse();
		this.editForm.expand();

		var record = grid.getStore().getAt(rowIndex);
		var data = {};
		Ext.apply(data, record.data);
		data.organization = Main.app.getUser().organization.id;

		this.editForm.getForm().loadRecord({data: data});
		this.editForm.setTitle(MSG['edit.title']);
	},

	onSave: function() {
		var theForm = this.editForm.getForm();

		theForm.submit({
			url: CONTEXT_PATH + '/secure/orgadmin/unit/update.json',
			method: 'POST',
			clientValidation: true,
			waitTitle: MSG['wait.title'],
			waitMsg: MSG['wait.message'],
			success: this.onSaveSuccess,
			failure: this.onSaveError,
			scope: this
		});
	},

	onSaveSuccess: function(/*form, action*/) {
		notifySuccess(MSG['update'], MSG['update.success']);
		this.pageToolbar.onClick("refresh");
	},

	onSaveError: function(/*form, action*/) {
		notifyError(MSG['update'], MSG['update.error']);
	},

	onCancel: function() {
		this.editForm.getForm().reset();
		this.editForm.setTitle(MSG['button.newfem']);		
	}

	,onCheckRemoveSelected: function() {
		var selections = this.resultsGrid.getSelectionModel().getSelections();
		if (selections.length > 0){
			var elements = [];
			var i;
			for (i=0; i<selections.length; i++){
				elements.push(selections[i].get('id'));
			}

			Ext.Ajax.request({
				waitTitle: MSG['wait.title'],
				waitMsg: MSG['wait.message'],
				url: CONTEXT_PATH + '/secure/orgadmin/unit/checkdelete.json',
				success: function( result/*, request*/ ){
					if (result.responseText){
						var winCheck = new Org.UnitCheckDelete({data: result.responseText, searchPanel: this});

						winCheck.show();
					}
				},
				failure: function(){
					notifyError(MSG['error'], MSG['check.error']);
				},
				params: { elements: elements },
				scope: this
			});
		}
	},

	getToolbar: function(){
		return this.pageToolbar;
	},

	getEditForm: function(){
		return this.editForm;
	}

});


/**
 * Module definition.
 */
MODULES['6_units'] = {

	menu: null,

	init: function() {
		// Initialize common menu
		this.menu = new Ext.menu.Menu({
			items: [{
				text: MSG['unit.search'],
				iconCls: 'icon-unit-find',
				handler: this.onUnits,
				scope: this
			},{
				text: MSG['unit.new'],
				iconCls: 'icon-unit-add',
				handler: this.onNewUnit,
				scope: this
			}, {
				text: MSG['check.units.without.question'],
				iconCls: 'icon-checks',
				handler: this.onCheckUnitQuestions,
				scope: this
			}, {
				text: MSG['check.units.without.path'],
				iconCls: 'icon-checks',
				handler: this.onCheckUnitPaths,
				scope: this
			}, {
				text: MSG['check.units.without.qualification'],
				iconCls: 'icon-checks',
				handler: this.onCheckUnitQualifications,
				scope: this
			}, {
				text: MSG['check.units.without.action'],
				iconCls: 'icon-checks',
				handler: this.onCheckUnitActions,
				scope: this
			}]
		});


		// Add menu to toolbar
		Main.app.mainToolbar.add({
			text: MSG['units.title'],
			iconCls: 'icon-unit',
			menu: this.menu
		});
	},
	onUnits: function() {
		var searchPanel = new Org.UnitPanel();
		Main.app.addPanel(searchPanel);
	},

	onNewUnit: function() {
		var editDialog = new Org.UnitDialog();
		editDialog.show();
	},


	onCheckUnitQuestions: function() {
		var panel = new Common.CheckPanel({
			title: MSG['check.units.without.question'],
			emptyText: MSG['no.units.without.question'],
			checkName: 'units-questions',
			iconCls: 'icon-checks',
			storeFields: ['id', 'code', 'name', 'description'],
			columns: [{
				header: MSG['unit.id'], dataIndex: 'id', width: 30, sortable: true
			},{
				header: MSG['unit.code'], dataIndex: 'code', width: 60, sortable: true
			},{
				header: MSG['unit.name'], dataIndex: 'name', width: 130, sortable: true
			},{
				header: MSG['unit.description'], dataIndex: 'description', width: 200, sortable: true
			}]
		});
		Main.app.addPanel(panel);
	},

	onCheckUnitPaths: function() {
		var panel = new Common.CheckPanel({
			title: MSG['check.units.without.path'],
			emptyText: MSG['no.units.without.path'],
			checkName: 'units-paths',
			iconCls: 'icon-checks',
			storeFields: ['id', 'code', 'name', 'description'],
			columns: [{
				header: MSG['unit.id'], dataIndex: 'id', width: 30, sortable: true
			},{
				header: MSG['unit.code'], dataIndex: 'code', width: 60, sortable: true
			},{
				header: MSG['unit.name'], dataIndex: 'name', width: 130, sortable: true
			},{
				header: MSG['unit.description'], dataIndex: 'description', width: 200, sortable: true
			}]
		});
		Main.app.addPanel(panel);
	},

	onCheckUnitQualifications: function() {
		var panel = new Common.CheckPanel({
			title: MSG['check.units.without.qualification'],
			emptyText: MSG['no.units.without.qualification'],
			checkName: 'units-qualifications',
			iconCls: 'icon-checks',
			storeFields: ['id', 'code', 'name', 'description'],
			columns: [{
				header: MSG['unit.id'], dataIndex: 'id', width: 30, sortable: true
			},{
				header: MSG['unit.code'], dataIndex: 'code', width: 60, sortable: true
			},{
				header: MSG['unit.name'], dataIndex: 'name', width: 130, sortable: true
			},{
				header: MSG['unit.description'], dataIndex: 'description', width: 200, sortable: true
			}]
		});
		Main.app.addPanel(panel);
	},

	onCheckUnitActions: function() {
		var panel = new Common.CheckPanel({
			title: MSG['check.units.without.action'],
			emptyText: MSG['no.units.without.action'],
			checkName: 'units-actions',
			iconCls: 'icon-checks',
			storeFields: ['id', 'code', 'name', 'description'],
			columns: [{
				header: MSG['unit.id'], dataIndex: 'id', width: 30, sortable: true
			},{
				header: MSG['unit.code'], dataIndex: 'code', width: 60, sortable: true
			},{
				header: MSG['unit.name'], dataIndex: 'name', width: 130, sortable: true
			},{
				header: MSG['unit.description'], dataIndex: 'description', width: 200, sortable: true
			}]
		});
		Main.app.addPanel(panel);
	}
};
